package serial_handle

import (
	"data-system/common"
	"data-system/meta"
	"data-system/models"
	"data-system/tools"
	"fmt"
	"log"

	"github.com/spf13/cast"
)

func ExchangeDecodes(nodeType string, dbRows []models.NodeData) ([]models.ExcelData, error) {
	excelRows := make([]models.ExcelData, 0)
	for _, dbRow := range dbRows {
		excelRow, err := ExchangeDecode(nodeType, dbRow)
		if err != nil {
			return nil, err
		}
		excelRows = append(excelRows, excelRow)
	}
	return excelRows, nil
}

func ExchangeDecode(nodeType string, dbRow models.NodeData) (models.ExcelData, error) {
	var excelRow models.ExcelData
	serialMeta := meta.GetSerialMeta(nodeType)
	if serialMeta == nil {
		errorMsg := fmt.Sprintf("%v没有序列化元数据", nodeType)
		log.Println(errorMsg)
		return excelRow, fmt.Errorf(errorMsg)
	}
	var row = make(map[string]string)
	var originRow = make([]string, 0)

	for _, column := range serialMeta.Columns {
		ctx := models.BuildDecode(&column, &dbRow)
		handler, err := Router(ctx)
		if err != nil {
			log.Println(err.Error())
			return excelRow, err
		}
		ctx, err = handler.Decode()
		if err != nil {
			log.Println(err.Error())
			return excelRow, err
		}
		row[column.Name] = cast.ToString(ctx.ResultData)
		originRow = append(originRow, cast.ToString(ctx.ResultData))
	}
	excelRow = models.ExcelData{OriginRow: originRow, Row: row}
	return excelRow, nil
}

func ExchangeEncodes(nodeType string, excelRows []models.ExcelData) ([]models.NodeData, error) {
	dbRows := make([]models.NodeData, 0)
	for _, excelRow := range excelRows {
		dbRow, err := ExchangeEncode(nodeType, excelRow)
		if err != nil {
			return nil, err
		}
		dbRows = append(dbRows, dbRow)
	}
	return dbRows, nil
}

func ExchangeEncode(nodeType string, excelRow models.ExcelData) (models.NodeData, error) {
	var dbRow models.NodeData
	serialMeta := meta.GetSerialMeta(nodeType)
	if serialMeta == nil {
		errorMsg := fmt.Sprintf("%v没有序列化元数据", nodeType)
		log.Println(errorMsg)
		return dbRow, fmt.Errorf(errorMsg)
	}
	var dbRowData = make(map[string]interface{})
	for _, column := range serialMeta.Columns {
		ctx := models.BuildEncode(&column, &excelRow)
		handler, err := Router(ctx)
		if err != nil {
			log.Println(err.Error())
			return dbRow, err
		}
		ctx, err = handler.Encode()
		if err != nil {
			log.Println(err.Error())
			return dbRow, err
		}
		dbRowData[column.Name] = ctx.ResultData
	}
	id := dbRowData[common.ColumnId].(int64)
	dbRow = models.BuildNodeData(nodeType, tools.Md5(excelRow.OriginRow), common.StatNone, id, dbRowData)
	return dbRow, nil
}
